﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace YKPrintService.Util
{
    /// <summary>
    /// JSON辅助操作类
    /// </summary>
    public class JsonHelper
    {
        public static string Object2Json(object obj)
        {
            if (obj != null)
            {
                return JsonConvert.SerializeObject(obj);
            }
            return "";
        }

        public static T Json2Object<T>(string jsonString)
        {
            if (!string.IsNullOrEmpty(jsonString))
            {
                return JsonConvert.DeserializeObject<T>(jsonString);
            }
            return default(T);
        }

        /// <summary>
        /// xml字符串转json字符串
        /// </summary>
        /// <param name="xmlstring"></param>
        /// <returns></returns>
        public static string Xml2Json(string xmlstring)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(xmlstring);
                return JsonConvert.SerializeXmlNode(doc);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// XmlDocument转json字符串
        /// </summary>
        /// <param name="xmlstring"></param>
        /// <returns></returns>
        public static string XmlDoc2Json(XmlDocument doc)
        {
            try
            {
                return JsonConvert.SerializeXmlNode(doc);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// Json转Xml
        /// </summary>
        /// <param name="jsonstring"></param>
        /// <returns></returns>
        public static string Json2Xml(string jsonstring)
        {
            try
            {
                XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonstring);
                return doc.OuterXml;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// Json转Xml
        /// </summary>
        /// <param name="jsonstring"></param>
        /// <returns></returns>
        public static XmlDocument Json2XmlDoc(string jsonstring)
        {
            try
            {
                return JsonConvert.DeserializeXmlNode(jsonstring);
            }
            catch
            {
                return null;
            }
        }
    }
}
